import 'package:flutter/material.dart';
import 'package:flutter_page_flip/flutter_page_flip.dart';
import 'dart:math';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Page Flip Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Page Flip Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
  late PageFlipController _controller;
  final Random _random = Random();
  static const int _totalPages = 100; // 100页用于测试

  @override
  void initState() {
    super.initState();
    _controller = PageFlipController(
      config: const PageFlipConfig(
        animation: PageFlipAnimation.cover,
        animationDuration: 300, // 增加动画时长到500ms，让效果更明显
        enableGestures: true,
        enableTapToFlip: true,
        oneHandMode: false, // 正常模式：左侧点击=上一页，右侧点击=下一页
        flipVelocityThreshold: 400.0, // 更敏感的速度阈值
        flipDistanceThreshold: 0.10, // 滑动10%就能翻页
      ),
      pageCount: _totalPages,
      pageBuilder: (index) => _buildPage(index),
      onPageChanged: (index) {
        print('页面切换到: ${index + 1}');
      },
    );
    _controller.initAnimationControllers(this);
  }

  /// 随机跳转到任意页面 (0-99)
  void _randomJump() {
    final targetPage = _random.nextInt(_totalPages);
    print('🎲 随机跳转到第${targetPage + 1}页');
    _controller.goToPage(targetPage, animate: false); // 大范围跳转不使用动画
  }

  /// 构建页面内容
  Widget _buildPage(int index) {
    // 使用15种不同颜色循环
    final colors = [
      Colors.red[100]!,
      Colors.blue[100]!,
      Colors.green[100]!,
      Colors.orange[100]!,
      Colors.purple[100]!,
      Colors.teal[100]!,
      Colors.pink[100]!,
      Colors.amber[100]!,
      Colors.cyan[100]!,
      Colors.lime[100]!,
      Colors.indigo[100]!,
      Colors.brown[100]!,
      Colors.grey[100]!,
      Colors.deepOrange[100]!,
      Colors.lightGreen[100]!,
    ];

    final color = colors[index % colors.length];

    return Container(
      color: color,
      child: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(20.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              // 页面信息
              Card(
                elevation: 4,
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Column(
                    children: [
                      Text(
                        '第 ${index + 1} 页',
                        style:
                            Theme.of(context).textTheme.headlineLarge?.copyWith(
                                  fontWeight: FontWeight.bold,
                                  color: Theme.of(context).primaryColor,
                                ),
                      ),
                      const SizedBox(height: 8),
                      Text(
                        '共 $_totalPages 页',
                        style: Theme.of(context).textTheme.bodyLarge,
                      ),
                      const SizedBox(height: 4),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          if (_controller.isFirstPage)
                            const Chip(
                              label: Text('首页'),
                              backgroundColor: Colors.green,
                            ),
                          if (_controller.isLastPage)
                            const Chip(
                              label: Text('末页'),
                              backgroundColor: Colors.red,
                            ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),

              const SizedBox(height: 30),

              // 主要随机跳转按钮
              ElevatedButton.icon(
                onPressed: _randomJump,
                icon: const Icon(Icons.shuffle, size: 28),
                label: const Text(
                  '随机跳转 (0-99页)',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                ),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Theme.of(context).primaryColor,
                  foregroundColor: Colors.white,
                  padding:
                      const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
              ),

              const SizedBox(height: 30),

              // 快速跳转按钮组
              Wrap(
                spacing: 12,
                runSpacing: 12,
                children: [
                  ElevatedButton(
                    onPressed: () => _controller.goToPage(0, animate: false),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.green,
                      foregroundColor: Colors.white,
                    ),
                    child: const Text('首页'),
                  ),
                  ElevatedButton(
                    onPressed: () =>
                        _controller.goToPage(49, animate: false), // 第50页
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.orange,
                      foregroundColor: Colors.white,
                    ),
                    child: const Text('第50页'),
                  ),
                  ElevatedButton(
                    onPressed: () =>
                        _controller.goToPage(_totalPages - 1, animate: false),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.red,
                      foregroundColor: Colors.white,
                    ),
                    child: const Text('末页'),
                  ),
                ],
              ),

              const SizedBox(height: 20),

              // 相邻翻页按钮（有动画）
              ListenableBuilder(
                listenable: _controller,
                builder: (context, child) {
                  return Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      ElevatedButton.icon(
                        onPressed: _controller.isFirstPage
                            ? null
                            : () => _controller.previousPage(),
                        icon: const Icon(Icons.arrow_back),
                        label: const Text('上一页'),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.blue,
                          foregroundColor: Colors.white,
                        ),
                      ),
                      ElevatedButton.icon(
                        onPressed: _controller.isLastPage
                            ? null
                            : () => _controller.nextPage(),
                        icon: const Icon(Icons.arrow_forward),
                        label: const Text('下一页'),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.blue,
                          foregroundColor: Colors.white,
                        ),
                      ),
                    ],
                  );
                },
              ),

              const SizedBox(height: 40),

              // 使用说明
              Card(
                color: Colors.blue[50],
                child: const Padding(
                  padding: EdgeInsets.all(16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '📖 使用说明:',
                        style: TextStyle(
                            fontWeight: FontWeight.bold, fontSize: 16),
                      ),
                      SizedBox(height: 8),
                      Text('• 左右滑动翻页 (滑动10%距离即可，有动画)'),
                      Text('• 左侧点击 = 上一页，右侧点击 = 下一页 (有动画)'),
                      Text('• 上一页/下一页按钮 = 平滑翻页动画 (0.4秒)'),
                      Text('• 大范围跳转按钮 = 无动画直接切换'),
                      Text('• 随机跳转 = 无动画直接切换'),
                      Text('• 速度超过400px/s也会触发翻页'),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        actions: [
          IconButton(
            icon: const Icon(Icons.shuffle),
            onPressed: _randomJump,
            tooltip: '随机跳转',
          ),
        ],
      ),
      body: PageFlipWidget(
        controller: _controller,
      ),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}
